<template>
  <div class="about" style="padding: 10px">
    <!-- 查询、新增 -->
    <el-form
      :inline="true"
      class="demo-form-inline"
      style="margin: 10px 0"
    >
      <el-form-item label="类型名">
        <el-input
          type="text"
          placeholder="请输入类型名"
          v-model="post.postTypeName"
        ></el-input>
      </el-form-item>
      <el-form-item label="标题">
        <el-input
          type="text"
          placeholder="请输入标题"
          v-model="post.title"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input
          type="text"
          placeholder="请输入用户名"
          v-model="post.username"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getPost()" type="primary">查询</el-button>
        <el-button @click="handleAdd()" type="primary">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 表 -->
    <el-table
      v-loading="loading"
      stripe
      border
      :data="posts"
      style="width: 100%; height: 500px; overflow: auto; "
    >
      <el-table-column prop="postId" label="编号" sortable width="70"  align="center"></el-table-column>
      <el-table-column prop="username" label="用户名" width="70"  align="center">
      </el-table-column>
      <el-table-column prop="title" label="标题" width="130"  align="center"> </el-table-column>
      <el-table-column prop="postTypeName" label="类型名" width="140"  align="center">
      </el-table-column>
      <el-table-column prop="introduction" label="简介" width="120"  align="center">
      </el-table-column>

      <el-table-column prop="mediaLink" label="封面" width="120"  align="center">
        <template v-slot="{ row }">
          <el-image style="width: 120px; height:70px" :src="row.mediaLink" :preview-src-list="[row.mediaLink]" />
        </template>
      </el-table-column>
      <el-table-column prop="tag" label="标签" width="140"  align="center">
        <template v-slot="{ row }">
          <el-tag
            type="primary"
            v-for="(item1, index) in JSON.parse(row.tag)"
            :key="index"
            style="margin-right: 10px; font-size: 12px"
            >{{ item1 }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column prop="status" label="审核状态" width="80"  align="center">
        <template v-slot="{ row }">
          <span v-if="row.status === 1">已审核</span>
          <span v-else-if="row.status === 0">待审核</span>
        </template>
      </el-table-column>
      <el-table-column prop="visibility" label="可见范围" width="80"  align="center">
      </el-table-column>
      <el-table-column prop="isDeleted" label="是否删除" width="80"  align="center">
        <template v-slot="{ row }">
          <span v-if="row.isDeleted === 1">是</span>
          <span v-else-if="row.isDeleted === 0">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="postDate" label="发布日期" width="140"  align="center">
      </el-table-column>

      <el-table-column label="操作"  align="center">
        <!-- 通过 Scoped slot 可以获取到 row, column, $index 和 store（table 内部的状态管理）的数据 -->
        <template #default="scope">
          <!-- 编辑 执行的函数 handleEdit,索引和整个数据行"对象"-->
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >审核</el-button
          >
          <!-- 删除的时候 执行的函数 handleDelete -->
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block" style="margin-top: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalElements"
      >
      </el-pagination>
    </div>

    <!--修改、新增的dialog界面 -->
    <el-dialog
      :title="title"
      v-model="dialogFormVisible"
      width="60%"
      top="5px"
    >
      <el-form :model="updatepost">
        <el-form-item
          label="用&nbsp;户&nbsp;&nbsp;名"
          :label-width="formLabelWidth"
        >
          <el-input v-model="updatepost.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item
          label="标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;题"
          :label-width="formLabelWidth"
        >
          <el-input v-model="updatepost.title" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item
          label="类&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型"
          :label-width="formLabelWidth"
        >
          <el-select v-model="updatepost.postTypeId" style="width: 100%" disabled>
            <el-option
              v-for="item in postTypes"
              :key="item.postTypeId"
              :value="item.postTypeId"
              :label="item.postTypeName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="简&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;介"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="updatepost.introduction"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="封&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;面"
          :label-width="formLabelWidth"
          disabled
        >
          <div style="text-align: left; margin-left: 6%">
            <el-image style="width: 120px; height:70px" :src="imgurl" :preview-src-list="[imgurl]" />
          </div>
        </el-form-item>
        <el-form-item
          label="标&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;签"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="tagsArr"
            multiple
            filterable
            allow-create
            default-first-option
            style="width: 100%"
            disabled
          >
            <el-option value="猫"></el-option>
            <el-option value="狗"></el-option>
            <el-option value="乌龟"></el-option>
            <el-option value="鱼"></el-option>
            <el-option value="鸟"></el-option>
            <el-option value="宠物"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态" :label-width="formLabelWidth">
          <el-select v-model="updatepost.status" style="width: 100%">
            <el-option :value="0" label="待审核"></el-option>
            <el-option :value="1" label="已审核"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" :label-width="formLabelWidth">
          <el-select v-model="updatepost.visibility" style="width: 100%" disabled>
            <el-option :value="'公开'" label="公开"></el-option>
            <el-option :value="'私密'" label="私密"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除" :label-width="formLabelWidth" >
          <el-select v-model="updatepost.isDeleted" style="width: 100%" disabled>
            <el-option :value="0" label="否"></el-option>
            <el-option :value="1" label="是"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="内&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;容" 
          prop="content"
          style="margin-left: 52px"
        >
          <div id="editor" style="text-align: justify; width: 80%" ></div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatePost">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
//富文本
import E from "wangeditor";
import hljs from "highlight.js";
import { policy } from "@/components/upload/policy";
import { getUUID } from "@/utils";
import $ from "jquery";


export default {
  name: "PostExamManage",
  components: {},
  data() {
    return {
      //临时展示的图片
      imgurl: "",
      //方便于更新数据
      postId: "",
      //有一个对象 保存了从后端返回的结果，同时这个数据可以和页面的模板语法中变量关联
      //可以实时响应 ,这里数组 [] 和后端返回的 []关联
      posts: [], //查询的帖子信息
      totalElements: 1, //总条数
      currentPage: 1, //当前页
      pageSize: 6, //条数
      pages: 1, //页数
      //这里写了一个对象，包含post对象中的属性
      post: {}, //查询条件用户信息
      dialogFormVisible: false,
      //要修改、新增的post数据，和表单内容相关
      updatepost: {},
      //指定修改、新增标题
      title: "",
      formLabelWidth: "120px",
      tagsArr: [], //用于新增、修改存储标签
      postTypes: [], //用于存储所有可以选择可类型
      editor: null, //富文本
      users: [], //用于存储所有用户
    };
  },
  created() {
    this.getPost();
    this.getPostType();
    this.getUsers();
  },
  //自定义函数都可以写在 {}
  methods: {
    //新增
    handleAdd: function () {
      this.title = "新增";
      //清空数据
      this.updatepost = {};
      this.tagsArr = [];
      this.imgurl = "";
      this.setRichText();
      
      //对话框显示
      this.dialogFormVisible = true;
    },

    //更新和新增
    updatePost: function () {
      this.updatepost.mediaLink = this.imgurl;
      this.updatepost.tag = JSON.stringify(this.tagsArr);
      this.updatepost.content = this.editor.txt.html();
      //调用后端修改接口
      request
        .put("/post/", JSON.stringify(this.updatepost))
        .then((res) => {
          //请求成功后
          //这里简化了
          if (res.code === 0) {
            //提示成
            this.$message({
              showClose: true,
              message: res.msg,
              type: "success",
            });

            //关闭窗口
            this.dialogFormVisible = false;
            //重新加载数据
            this.getPost();
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //查询
    getPost: function () {
      //调用后端接口，返回数据,要使用axios,post请求
      // axios.post(url,json,{headers:{}}).then()
      this.loading=true
      request
        .post(
          "/post/pageExam?pageNum=" +
            this.currentPage +
            "&pageSize=" +
            this.pageSize,
          JSON.stringify(this.post)
        )
        .then((res) => {
          //请求成功后
          // =>res.data中
          this.posts = res.data.list;
          this.totalElements = res.data.total;
          this.currentPage = res.data.pageNum;
          this.pages = res.data.pages;
          this.loading=false
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //查询帖子类型
    getPostType: function () {
      request
        .get("/postType/select")
        .then((res) => {
          this.postTypes = res.data;
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //查询所有用户
    getUsers: function () {
      request
        .post("/userinfo/page")
        .then((res) => {
          //请求成功后
          // =>res.data中
          this.users = res.data.list;
        })
        .catch((err) => {
          console.log("axios error: " + err);
        });
    },
    //修改
    handleEdit(index, row) {
      //设置dialogFormVisible 的值为true
      this.title = "修改";
      this.dialogFormVisible = true;
      this.updatepost = row;
      this.tagsArr = JSON.parse(row.tag || "[]");
      this.imgurl = row.mediaLink;
      this.setRichText();
      setTimeout(() => {
        this.editor.txt.html(row.content);
      }, 0);
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("此操作将逻辑删除该帖子是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        //确定
        .then(() => {
          request.delete("/post/" + row.postId).then((res) => {
            if (res.code === 0) {
              //提示成功
              this.$message({
                showClose: true,
                message: "删除成功!",
                type: "success",
              });
              //重新加载数据
              this.getPost();
            } else {
              this.$message({
                showClose: true,
                message: "删除失败!",
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          //取消
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //改变每页记录数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //当前用户选择的每页显示几条记录呢
      this.pageSize = val;
      this.currentPage = 1;
      //重新调用
      this.getPost();
    },
    //翻页(点击页码)
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getPost(); // 获取新的数据
    },
    //富文本
    setRichText() {
      this.$nextTick(() => {
        if (this.editor != null) {
          this.editor.destroy(); //这里做了一次判断，判断编辑器是否被创建，如果创建了就先销毁。
        }
        this.editor = new E("#editor");

        //不需要使用i18next时设置为null，要不然控制台第二次初始化的时候会把报错
        this.editor.i18next = null;
        this.editor.highlight = hljs;
        
        this.editor.config.customUploadImg = (files, insertImgFn) => {
          // 获取签名等信息，此处使用 policy() 方法
          policy()
            .then((response) => {
              console.log(response.data);
              let key = response.data.dir + getUUID() + "_${filename}";
              let url =
                response.data.host +
                "/" +
                key.replace("${filename}", files[0].name);
              const formData = new FormData();
              formData.append("key", key);
              formData.append("ossaccessKeyId", response.data.accessid);
              formData.append("policy", response.data.policy);
              formData.append("signature", response.data.signature);
              formData.append("dir", response.data.dir);
              formData.append("host", response.data.host);
              formData.append("file", files[0]); // 只上传第一个文件，你可以根据需求修改
              console.log(url);
              // 通过 AJAX 或其他方法上传图片到阿里云 OSS
              $.ajax({
                url: response.data.host,
                type: "POST",
                contentType: false,
                processData: false,
                data: formData,
                success: function (res) {
                  // 上传成功后处理
                  insertImgFn(url);
                },
                error: function (res) {
                  console.error(res);
                },
              });
            })
            .catch((err) => {
              console.error(err);
            });
        };

        this.editor.create(); // 创建
        this.editor.disable();
      });
    },
  },
};
</script>

